<?php

namespace app\admin\model\manufacture;

use think\Model;

class Quality extends Model
{
    // 表名
    protected $name = 'manufacture_quality';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    
    // 追加属性
    protected $append = [
        'status_text',
        'type_text',
        'result_text'
    ];
    
    // 状态
    public function getStatusList()
    {
        return [
            '1' => __('启用'),
            '0' => __('停用')
        ];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['status'];
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    // 类型
    public function getTypeList()
    {
        return [
            'incoming' => __('来料检验'),
            'process' => __('过程检验'),
            'final' => __('最终检验'),
            'special' => __('特殊检验')
        ];
    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['type'];
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    // 结果
    public function getResultList()
    {
        return [
            'pass' => __('合格'),
            'fail' => __('不合格'),
            'pending' => __('待检验')
        ];
    }

    public function getResultTextAttr($value, $data)
    {
        $value = $value ? $value : $data['result'];
        $list = $this->getResultList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    // 关联产品型号
    public function productModel()
    {
        return $this->belongsTo('app\admin\model\scanwork\ProductModel', 'product_model_id', 'id');
    }

    // 关联质检标准
    public function standard()
    {
        return $this->belongsTo('QualityStandard', 'standard_id', 'id');
    }

    // 关联检验员
    public function inspector()
    {
        return $this->belongsTo('app\admin\model\Admin', 'inspector_id', 'id');
    }

    // 获取合格率
    public function getPassRateAttr($value, $data)
    {
        if ($data['total_quantity'] > 0) {
            return round(($data['pass_quantity'] / $data['total_quantity']) * 100, 2);
        }
        return 0;
    }

    // 获取不合格率
    public function getFailRateAttr($value, $data)
    {
        if ($data['total_quantity'] > 0) {
            return round(($data['fail_quantity'] / $data['total_quantity']) * 100, 2);
        }
        return 0;
    }
}
